package com.study.zookeeperAPI;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.util.List;
import java.util.concurrent.CountDownLatch;

public class GetChildrenAsync implements Watcher {

    private static CountDownLatch latch = new CountDownLatch(1);
    private static ZooKeeper zooKeeper = null;

    public static void main(String[] args) {

        System.out.println("hahahah=================");
        String connectStr = "127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2184";
        //每5s发送一次心跳
        int session_time = 5000;
        try{
            zooKeeper = new ZooKeeper(connectStr, session_time, new GetChildrenAsync());
            latch.await();
            String path = "/zk-book";
            //zooKeeper.create(path,"".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            zooKeeper.create(path +"/c1", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
            zooKeeper.getChildren(path,true, new IChildren2Callback(), null);
            zooKeeper.create(path + "/c2", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
            Thread.sleep(Integer.MAX_VALUE);
        }catch (Exception e){
            System.out.println("error======" + e.getMessage());
        }

    }

    public void process(WatchedEvent watchedEvent) {
        if(Event.KeeperState.SyncConnected == watchedEvent.getState()){
            if(Event.EventType.None == watchedEvent.getType() && null == watchedEvent.getPath()){
                latch.countDown();
            }
            else if(watchedEvent.getType() == Event.EventType.NodeChildrenChanged){
                try{
                    System.out.println("ReGet Child: "+ zooKeeper.getChildren(watchedEvent.getPath(), true));
                }catch (Exception e){
                    System.out.println("Exception-----" + e.getMessage());
                }
            }
        }
    }

    static class IChildren2Callback implements AsyncCallback.Children2Callback{
        public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) {
            System.out.println("Get Children znode result: [response code:" + rc + ", oaram path:" + path + ",ctx:" + ctx + ", children list:" + children
            + ", stat:" + stat);
        }
    }
}
